//
//  MILRadarWarningViewController.m
//  MicrowaveInteractionLight
//
//  Created by maple on 2016/12/17.
//  Copyright © 2016年 maple. All rights reserved.
//

#import "MILRadarWarningViewController.h"
#import "MILRadarWarningTableViewCell.h"
#import "SettingWarnApi.h"

@interface MILRadarWarningViewController ()<MILRadarWarningCellDelegate>
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property(nonatomic,copy)NSString *myAlertString;
@property(nonatomic,copy)NSString *myDeviceIDString;

/** 空数据提示 */
@property (nonatomic,strong) UILabel *emptyLabel;
@end

@implementation MILRadarWarningViewController
#pragma mark -- UI

//- (void)dealloc
//{
//    [[NSNotificationCenter defaultCenter]removeObserver:self];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //初始化UI
    [self initMILRadarWarningView];
    
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(deviceStateChange:) name:@"DeviceStateNotification" object:nil];
}

//- (void)deviceStateChange:(NSNotification *)notify{
//    NSString *content = notify.object;
//    NSDictionary *dic = notify.userInfo;
//    if ([dic[@"backCode"] isEqualToString:@"1805"]){
//        if (content.length == 2) {
//            for (MILUserDeviceModel *model in self.myDataSourceArray) {
//                if ([model.mac isEqualToString:dic[@"macAddress"]]) {
//                    if ([content isEqualToString:@"01"]) {
//                        model.is_alert = @"1";
//                    } else {
//                        model.is_alert = @"0";
//                    }
//                }
//            }
//            [SVProgressHUD showSuccessWithStatus:@"操作成功"];
//            [self.myTableView reloadData];
//            //            [self getUserDeviceList];
//        }
//    }
//    
//}

//初始化UI
- (void)initMILRadarWarningView
{
    
    [self.emptyLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view);
    }];
    
    
    [self.myTableView registerNib:[UINib nibWithNibName:@"MILRadarWarningTableViewCell" bundle:nil] forCellReuseIdentifier:@"MILRadarWarningTableViewCell"];
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;

}

- (void)refreshBaseControlValue
{
    [self setNavigationBarTitle:@"雷达预警"];
    
    if (self.myDataSourceArray.count == 0) {
        self.emptyLabel.hidden = NO;
    } else {
        self.emptyLabel.hidden = YES;
    }
    
}

#pragma mark UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.myDataSourceArray.count>0)
    {
        return self.myDataSourceArray.count;
    }
    return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     MILRadarWarningTableViewCell *Cell=[tableView  dequeueReusableCellWithIdentifier:@"MILRadarWarningTableViewCell"];
    if (self.myDataSourceArray.count>0)
    {
        MILUserDeviceModel *model = self.myDataSourceArray[indexPath.row];
        //isopen
        if ([model.is_open isEqualToString:@"1"]) {
            Cell.myDeviceImageView.image = [UIImage imageNamed:@"liangdeng"];
        } else{
            Cell.myDeviceImageView.image = [UIImage imageNamed:@"deng"];
        }
        
        if ([model.is_alert isEqualToString:@"1"]) {
            [Cell.mySwitchBtn setBackgroundImage:[UIImage imageNamed:@"openLight"] forState:UIControlStateNormal];
            [Cell.mySwitchBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 15)];
            [Cell.mySwitchBtn setTitle:@"ON" forState:UIControlStateNormal];
        } else {
            [Cell.mySwitchBtn setBackgroundImage:[UIImage imageNamed:@"closeLight"] forState:UIControlStateNormal];
            [Cell.mySwitchBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 20, 0, 0)];
            [Cell.mySwitchBtn setTitle:@"OFF" forState:UIControlStateNormal];
        }
        if ([model.is_online isEqualToString:@"1"]) {
            Cell.myWifiStatusImageView.image = [UIImage imageNamed:@"icon_wifi_online"];
        } else {
            Cell.myWifiStatusImageView.image = [UIImage imageNamed:@"icon_wifi_offline"];
        }
        
        //计算宽度
        CGSize nickSize = [model.name sizeWithFont:[UIFont systemFontOfSize:18.0] maxSize:CGSizeMake(MAXFLOAT, 0)];
        Cell.myDeviceNameLabel.text = model.name;
        Cell.myDeviceNameLabelWidthLayout.constant = nickSize.width;
        [Cell.myDeviceNameLabel layoutIfNeeded];
        Cell.delegate = self;
    }
    
    return Cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return   0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 0.1;
}

#pragma mark -- MILRadarWarningCellDelegate
- (void)radarStatusSwitchCHangeClickButton:(UIButton *)btn
{
    MILRadarWarningTableViewCell * cell = nil;
    if ([btn isKindOfClass:[UIButton class]])
    {
        cell = (MILRadarWarningTableViewCell *)[[btn superview] superview];
    }
    
    NSIndexPath *indexPath = [self.myTableView indexPathForCell:cell];
    MILUserDeviceModel *model = self.myDataSourceArray[indexPath.row];
    if ([model.is_online isEqualToString:@"0"]) {
        [SVProgressHUD showErrorWithStatus:@"Wi-Fi不在线"];

        return;
    }
    
    if ([model.is_alert isEqualToString:@"1"])
    {
        btn.selected = NO;
        ThemeAlertView *alertView = [[ThemeAlertView alloc]initWithType:1];
        [self.view addSubview:alertView];
        
        [alertView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self.view);
        }];
        alertView.textLabel.text = @"主人，您到家了吗？确认关闭雷达预警功能吗？";
        [alertView.enterButton setTitle:@"关闭" forState:UIControlStateNormal];
        alertView.imageView.image = [UIImage imageNamed:@"radar"];
        [alertView callinAnimation];
        alertView.enter_block = ^(UIButton *sender) {
            [self setAlertWithMac:model.mac andState:@"0" andDeviceID:model.device_id];
            model.is_alert = [model.is_alert isEqualToString:@"1"]?@"0":@"1";
            self.myAlertString = model.is_alert;
            self.myDeviceIDString = model.device_id;
        };
        alertView.cancel_block = ^(UIButton *sender) {
        };

    }
    else
    {
        btn.selected = YES;
        //打开警报
        ThemeAlertView *alertView = [[ThemeAlertView alloc]initWithType:1];
        [self.view addSubview:alertView];
        
        [alertView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self.view);
        }];
        alertView.textLabel.text = @"开启预警功能倒计时60秒离开家的时间，当重新回到室内倒计时在20秒内客户没有关闭预警功能，则辨识为非法闯入。";
        [alertView.enterButton setTitle:@"开启" forState:UIControlStateNormal];
        alertView.imageView.image = [UIImage imageNamed:@"radar"];
        [alertView callinAnimation];
        alertView.enter_block = ^(UIButton *sender) {
            [self setAlertWithMac:model.mac andState:@"1" andDeviceID:model.device_id];
            model.is_alert = [model.is_alert isEqualToString:@"1"]?@"0":@"1";
            self.myAlertString = model.is_alert;
            self.myDeviceIDString = model.device_id;
        };
        alertView.cancel_block = ^(UIButton *sender) {
        };
    }

    
//    [self.myTableView reloadData];
}

- (void)setAlertWithMac:(NSString *)mac andState:(NSString *)state andDeviceID:(NSString *)deviceID{
//    NSString *string = [NSString stringWithFormat:@"0%@",state];
//    [[DTCloudManager defaultJNI_iOS_SDK]sendCommandForLocalByFunctionCode:@"1005" functionCommand:string deviceMacAddress:mac];
    SettingWarnApi *api = [[SettingWarnApi alloc]initWithDictionary:@{@"device_id":deviceID,@"alert":state}];
    [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
        NSDictionary * myDic = [request responseJSONObject];
        NSLog(@"my Dic == %@ ",myDic);
        if ([myDic[@"errcode"] intValue] == 0) {
            [SVProgressHUD showSuccessWithStatus:@"操作成功"];
            [self.myTableView reloadData];
        }else{
            [SVProgressHUD showErrorWithStatus:myDic[@"errmsg"]];
        }
    } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
        
    }];

}


#pragma mark -- 懒加载
- (UILabel *)emptyLabel{
    
    if (!_emptyLabel) {
        _emptyLabel = [[UILabel alloc]init];
        _emptyLabel.text = @"暂无设备";
        _emptyLabel.font = [UIFont systemFontOfSize:15];
        _emptyLabel.textColor = [UIColor colorWithRed:151/255.0 green:151/255.0 blue:151/255.0 alpha:1];
        [self.view addSubview:_emptyLabel];
    }
    return _emptyLabel;
}

@end
